<?php

namespace app\api\logic;

use app\common\enum\PayEnum;
use app\common\enum\user\AccountLogEnum;
use app\common\logic\AccountLogLogic;
use app\common\model\card\{Card, CardBin, CardOperationLog};
use think\facade\Config;
use app\common\model\user\{UserGroup, User};
use app\common\logic\BaseLogic;
use think\facade\Db;
use payment\{WorldFirstService, AirwallexService, SlashService};
use app\common\model\finance\TransactionNotification;

/**
 * card逻辑
 * Class CardLogic
 * @package app\api\logic
 */
class CardLogic extends BaseLogic
{

    /**
     * @notes 添加card
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/09 19:15
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {

            // 添加文件锁
            $lockKey = 'card_create_' . $params['user_info']['group_id'];
            if (!cache()->set($lockKey, 1, 10)) {  // 10秒锁
                throw new \Exception('操作太频繁，请稍后再试');
            }

            //单次开卡不能超过10张
            if ($params['card_num'] > 200) {
                throw new \Exception('单次开卡不能超过200张');
            }

            //计算预开卡是否足够
            if ($params['card_bin'] == 99) {
                $slashNum = Card::whereNull('user_id')
                    ->where('card_bin', $params['card_bin'])
                    ->count();
                if ($slashNum < $params['card_num']) {
                    throw new \Exception('预开卡数量不足,请联系管理员');
                }
            }


            //计算团队余额是否大于开卡金额
            $userGroup = UserGroup::where('id', $params['user_info']['group_id'])->findOrEmpty();
            if (empty($userGroup)) {
                throw new \Exception('团队不存在');
            }
            //计算可用卡位是否足够
//            $cardCount = Card::where('group_id', $params['user_info']['group_id'])->count();
            if (($userGroup->card_sum - $userGroup->card_used) < $params['card_num']) {
                throw new \Exception('可用卡位不足,当前已用卡位数量:' . $userGroup->card_used);
            }


            $user_money = $userGroup->user_money;


//            查看卡bin是否存在
            $card_bin = CardBin::where(['bin_id' => $params['card_bin'], 'group_id' => $params['user_info']['group_id']])->find();
            if (empty($card_bin)) {
                throw new \Exception('卡bin不存在');
            }

            $card_fee = $card_bin->card_fee * $params['card_num'];
            $card_money = $params['available_balance'] * $params['card_num'];

            // 验证参数
            if (!is_numeric($user_money) || !is_numeric($card_fee) || !is_numeric($card_money)) {
                throw new \Exception('无效的金额数据');
            }

            // 计算总费用
            $total_cost = bcadd($card_fee, $card_money, 2);

            // 比较余额
            if ($user_money <= 0) {
                throw new \Exception("余额不足,请充值");
            }

            if (bccomp($user_money, $total_cost, 2) < 0) {
                throw new \Exception("余额不足,请充值");
            }

            $userInfo = User::where(['id' => $params['user_id'], 'group_id' => $params['user_info']['group_id']])->find();
            if (empty($userInfo)) {
                throw new \Exception('用户不存在');
            }

            //组id
            $cardGroupId = '';
//            美国卡使用简称作为美国卡的卡组
            if ($params['card_bin'] == 12 || $params['card_bin'] == 15) {
                $slash = new SlashService($params['card_bin']);
                $groupParams = [
                    'filter:name' => $userGroup->abbreviation,
                ];
                $result = $slash->getCardGroup($groupParams);
                if (isset($result['items'][0]['id'])) {
                    $cardGroupId = $result['items'][0]['id'];
                } else {
                    $result = $slash->createCardGroup($userGroup->abbreviation);
                    $cardGroupId = $result['id'] ?? '';
                }
            }

//            根据卡bin开卡
            $start_no = $params['start_no'] ?? '';

            //开卡成功后入库
            for ($i = 0; $i < $params['card_num']; $i++) {
                $cardNum = $cardId = '';
                if ($start_no && $params['alias']) {
                    // 假设需要将数字格式化为至少三位数
                    $formatted_number = sprintf('%02d', $i + $start_no);
                    $alias = $params['alias'] . '-' . $formatted_number;
                } else {
                    $alias = $params['alias'];
                }

                //对接万里汇10，香港万里汇13
                if ($params['card_bin'] == 10 || $params['card_bin'] == 13) {
                    $j = 1000 + $i;
                    $cardNickName = date('YmdHis') . $params['user_id'] . $j;

                    //卡id和卡号随机值，由定时任务补充真实卡id和卡号
                    $cardId = $cardNickName;
                    $cardNum = $cardNickName;

                    //处理限额金额
                    if ($params['total_transaction_limit'] < 1) {
                        $params['total_transaction_limit'] = 200000;
                    }
                    if ($params['single_transaction_limit'] < 1) {
                        $params['single_transaction_limit'] = 50000;
                    }
                    if ($params['daily_transaction_limit'] < 1) {
                        $params['daily_transaction_limit'] = 100000;
                    }
                    if ($params['monthly_transaction_limit'] < 1) {
                        $params['monthly_transaction_limit'] = $params['total_transaction_limit'];
                    }

                }
                //对接空中云汇
                if ($params['card_bin'] == 11) {
                    $airwallex = new AirwallexService();
                    $cardNickName = date('YmdHis') . $params['user_id'] . rand(1000, 9999);
                    $data = [
                        'card_nickname' => $cardNickName,
                        'transaction_limits' => [
                            "currency" => "USD",
                            "limits" => []
                        ],
                    ];
                    if ($params['single_transaction_limit']) {
                        $data['transaction_limits']['limits'][] = [
                            "amount" => $params['single_transaction_limit'],
                            "interval" => "PER_TRANSACTION"
                        ];
                    }
                    if ($params['daily_transaction_limit']) {
                        $data['transaction_limits']['limits'][] = [
                            "amount" => $params['daily_transaction_limit'],
                            "interval" => "DAILY"
                        ];
                    }
                    if ($params['monthly_transaction_limit']) {
                        $data['transaction_limits']['limits'][] = [
                            "amount" => $params['monthly_transaction_limit'],
                            "interval" => "MONTHLY"
                        ];
                    }
                    if ($params['total_transaction_limit']) {
                        $data['transaction_limits']['limits'][] = [
                            "amount" => $params['total_transaction_limit'],
                            "interval" => "ALL_TIME"
                        ];
                    }
                    $airwallexResult = $airwallex->createVirtualCard($data);
                    if (!isset($airwallexResult['card_id'])) {
                        throw new \Exception('空中云付开卡失败，失败原因:' . $airwallexResult['message'] ?? '');
                    }
                    $cardId = $airwallexResult['card_id'];
                    $cardNum = $airwallexResult['card_number'];
                    if ($airwallexResult['card_status'] == 'ACTIVE') {
                        $cardStatus = 1;
                    } else {
                        $cardStatus = 0;
                    }
                }

                //对接slash card api方式
                if ($params['card_bin'] == 12) {
                    $cardNickName = $cardGroupId;
                    $j = 1000 + $i;
                    $cardId = $cardNum = $cardGroupId . date('YmdHis') . $params['user_id'] . $j;

                }

                Card::create([
                    'card_id' => $cardId,
                    'card_no' => $cardNum,
                    'card_bin' => $params['card_bin'],
                    'user_pid' => $userInfo['pid'],
                    'user_id' => $params['user_id'],
                    'available_balance' => $params['available_balance'] ?? 0,
                    'alias' => $alias ?? '',
                    'status' => $cardStatus ?? 1,
                    'card_nick_name' => $cardNickName ?? '',
                    'card_group_id' => $params['card_group_id'] ?? '',
                    'group_id' => $params['user_info']['group_id'] ?? '',
                    'tag_ids' => $params['tag_ids'] ?? '',
                    'single_transaction_limit' => $params['single_transaction_limit'] ?? '0',
                    'daily_transaction_limit' => $params['daily_transaction_limit'] ?? '0',
                    'monthly_transaction_limit' => $params['monthly_transaction_limit'] ?? '0',
                    'total_transaction_limit' => $params['total_transaction_limit'] ?? '0',
                    'create_time' => time(),
                ]);


            }
            //开卡费用
            $userGroup->user_money -= $total_cost;
            //已用卡位+1
            $userGroup->card_used += $params['card_num'];
            $userGroup->save();
            AccountLogLogic::add(
                $params['user_info']['group_id'],
                AccountLogEnum::UM_DEC_ADMIN,
                AccountLogEnum::DEC,
                $total_cost,
                '',
                '开卡数量:' . $params['card_num'] . ' 开卡费用:' . $total_cost,
            );

            // 操作完成后删除锁
            cache()->delete($lockKey);
            Db::commit();

            return true;

        } catch (\Exception $e) {
            // 操作完成后删除锁
            cache()->delete($lockKey);
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑card
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/04/09 19:15
     */
    public static function edit(array $params): bool
    {

        Db::startTrans();
        try {
            $data['update_time'] = time();

            //处理卡号和id关系
            if (isset($params['card_no']) && !isset($params['id'])) {
                $cardNos = explode("\n", $params['card_no']);
                foreach ($cardNos as &$cardNo) {
                    $cardNo = trim($cardNo);
                }
                $cardInfos = Card::whereIn('card_no', $cardNos)->select()->toArray();
            } else {
                $cardInfos = Card::whereIn('id', $params['id'])->select()->toArray();
            }

            $num = count($cardInfos);

            if ($num == 0) {
                self::setError('请选择卡片');
                return false;
            }


            foreach ($cardInfos as $k => $cardInfo) {
//            $cardInfo = Card::findOrEmpty($params['id']);
                if (empty($cardInfo)) {
                    self::setError('卡片不存在');
                    return false;
                }
                if ($cardInfo['group_id'] != $params['group_id']) {
                    self::setError('无权限');
                    return false;
                }

                if ($params['alias'] ?? '') {
                    if ($num == 1) {
                        $data['alias'] = $params['alias'];
                    } else {
                        $data['alias'] = $params['alias'] . '-' . ($k + 1);
                    }
                }

                if (isset($params['status'])) {
                    if ($params['status'] == 1) {
                        //激活卡片
                        $data['status'] = 1;
                        if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {
                            $wordFirstType = match ($cardInfo['card_bin']) {
                                10 => 'worldfirst',
                                13 => 'worldfirst_hk',
                            };
                            $worldFirst = new WorldFirstService($wordFirstType);
                            $worldFirst->updateCardStatus($cardInfo['card_id'], 'UNFREEZE');
                        }

                        //空中云付
                        if ($cardInfo['card_bin'] == 11) {
                            $airwallex = new AirwallexService();
                            $airwallex->updateCardStatus($cardInfo['card_id'], 'ACTIVE');
                        }
                        //slash:active, paused, inactive, closed
                        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
                            $slash = new SlashService($cardInfo['card_bin']);
                            $slash->setCardStatus($cardInfo['card_id'], 'active');
                        }
                    } else {
                        //冻结卡片
                        $data['status'] = 0;
                        if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {
                            $wordFirstType = match ($cardInfo['card_bin']) {
                                10 => 'worldfirst',
                                13 => 'worldfirst_hk',
                            };
                            $worldFirst = new WorldFirstService($wordFirstType);
                            $worldFirst->updateCardStatus($cardInfo['card_id'], 'FREEZE');
                        }

                        //空中云付
                        if ($cardInfo['card_bin'] == 11) {
                            $airwallex = new AirwallexService();
                            $airwallex->updateCardStatus($cardInfo['card_id'], 'INACTIVE');
                        }
                        //slash
                        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
                            $slash = new SlashService($cardInfo['card_bin']);
                            $slash->setCardStatus($cardInfo['card_id'], 'paused');
                        }
                    }
                }
                //更改运营id
                if (isset($params['user_id'])) {
                    $userInfo = User::findOrEmpty($params['user_id']);
                    if ($userInfo->isEmpty()) {
                        self::setError('用户不存在');
                        return false;
                    }
                    if ($userInfo['group_id'] != $params['group_id']) {
                        self::setError('无权限');
                        return false;
                    }
                    $data['user_id'] = $params['user_id'];
                }

                if (isset($params['remark'])) {
                    $data['remark'] = $params['remark'];
                }

                //更改组id
                if (isset($params['group_id'])) {
                    $data['group_id'] = $params['group_id'];
                }
                //更改card_group_id
                if (isset($params['card_group_id'])) {
                    $data['card_group_id'] = $params['card_group_id'];
                }

                //更改运营id
                if (isset($params['tag_ids'])) {
                    $data['tag_ids'] = $params['tag_ids'];
                }


                //兼容数值传空字符串的bug，为空则等于0
                if (isset($params['single_transaction_limit']) && $params['single_transaction_limit'] == '') $params['single_transaction_limit'] = 0;
                if (isset($params['daily_transaction_limit']) && $params['daily_transaction_limit'] == '') $params['daily_transaction_limit'] = 0;
                if (isset($params['monthly_transaction_limit']) && $params['monthly_transaction_limit'] == '') $params['monthly_transaction_limit'] = 0;
                if (isset($params['total_transaction_limit']) && $params['total_transaction_limit'] == '') $params['total_transaction_limit'] = 0;

                $limit = 0;
                //更改单笔限额
                if (isset($params['single_transaction_limit']) && $params['single_transaction_limit'] >= 0) {
                    $data['single_transaction_limit'] = $params['single_transaction_limit'];
                    $limit++;
                }
                if (isset($params['daily_transaction_limit']) && $params['daily_transaction_limit'] >= 0) {
                    $data['daily_transaction_limit'] = $params['daily_transaction_limit'];
                    $limit++;
                }
                if (isset($params['monthly_transaction_limit']) && $params['monthly_transaction_limit'] >= 0) {
                    $data['monthly_transaction_limit'] = $params['monthly_transaction_limit'];
                    $limit++;
                }
                if (isset($params['total_transaction_limit']) && $params['total_transaction_limit'] >= 0) {
                    $data['total_transaction_limit'] = $params['total_transaction_limit'];
                    $limit++;
                }

                //限额处理
                if ($limit == 4) {
                    //冻结的卡片不能修改限额 2025-8-4
                    if ($cardInfo['status'] == 0) {
                        $last4 = substr($cardInfo['card_no'], -4);
                        self::setError("卡片尾号{$last4}冻结,不能修改限额");
                        return false;
                    }
                    //对接万里汇
                    if ($cardInfo['card_bin'] == 10 || $cardInfo['card_bin'] == 13) {
                        $wordFirstType = match ($cardInfo['card_bin']) {
                            10 => 'worldfirst',
                            13 => 'worldfirst_hk',
                        };
                        $worldFirst = new WorldFirstService($wordFirstType);

                        //处理限额金额，万里付默认限额最大化，2025-7-15讨论
                        if ($params['total_transaction_limit'] < 1) {
                            $params['total_transaction_limit'] = 200000;
                        }
                        if ($params['single_transaction_limit'] < 1) {
                            $params['single_transaction_limit'] = 50000;
                        }
                        if ($params['daily_transaction_limit'] < 1) {
                            $params['daily_transaction_limit'] = 100000;
                        }
                        if ($params['monthly_transaction_limit'] < 1) {
                            $params['monthly_transaction_limit'] = $params['total_transaction_limit'];
                        }


                        //万里付限额处理
                        $worldFirstResult = $worldFirst->updateCardLimit([
                            'asset_id' => $cardInfo['card_id'],
                            'per_transaction_limit_max' => $params['single_transaction_limit'] * 100,
                            'daily_limit_max' => $params['daily_transaction_limit'] * 100,
                            'monthly_limit_max' => $params['monthly_transaction_limit'] * 100,
                            'per_card_limit_max' => $params['total_transaction_limit'] * 100,
                        ]);

                        //更新万里消费额度
                        $data['limit_money'] = $params['monthly_transaction_limit'];

                    }
                    //对接空中云汇
                    if ($cardInfo['card_bin'] == 11) {
                        $airwallex = new AirwallexService();
                        $limits = [
                            'card_id' => $cardInfo['card_id'],
                            'transaction_limits' => [
                                "currency" => "USD",
                                "limits" => []
                            ],
                        ];
                        if ($params['single_transaction_limit']) {
                            $limits['transaction_limits']['limits'][] = [
                                "amount" => $params['single_transaction_limit'],
                                "interval" => "PER_TRANSACTION"
                            ];
                        }
                        if ($params['daily_transaction_limit']) {
                            $limits['transaction_limits']['limits'][] = [
                                "amount" => $params['daily_transaction_limit'],
                                "interval" => "DAILY"
                            ];
                        }
                        if ($params['monthly_transaction_limit']) {
                            $limits['transaction_limits']['limits'][] = [
                                "amount" => $params['monthly_transaction_limit'],
                                "interval" => "MONTHLY"
                            ];
                        }
                        if ($params['total_transaction_limit']) {
                            $limits['transaction_limits']['limits'][] = [
                                "amount" => $params['total_transaction_limit'],
                                "interval" => "ALL_TIME"
                            ];
                        }

                        //空中云汇限额处理
                        $airwallexResult = $airwallex->updateCardLimit($limits);
                    }


                    //SLASH card
                    if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
                        //限额处理优先级:总>月>天
                        $limit = 0;
                        $preset = 'daily';
                        $single_transaction_limit = $params['single_transaction_limit'] ?? '0';
                        $daily_transaction_limit = $params['daily_transaction_limit'] ?? '0';
                        $monthly_transaction_limit = $params['monthly_transaction_limit'] ?? '0';
                        $total_transaction_limit = $params['total_transaction_limit'] ?? '0';
                        if ($daily_transaction_limit) {
                            $preset = 'daily';
                            $limit = $daily_transaction_limit;
                        }
                        if ($monthly_transaction_limit) {
                            $preset = 'monthly';
                            $limit = $monthly_transaction_limit;
                        }
                        if ($total_transaction_limit) {
                            $preset = 'collective';
                            $limit = $total_transaction_limit;
                        }
                        if ($limit) {
                            //注意，这里是美分，所以*100
                            $slashService = new SlashService($cardInfo['card_bin']);
                            $slashService->setCardRule($cardInfo['card_id'], $preset, $limit * 100, $single_transaction_limit * 100);
                        }
                    }
                }

                if (isset($params['remark'])) {
                    $data['remark'] = $params['remark'];
                }

                Card::update($data, ['id' => $cardInfo['id']]);
                $request = $params;
                unset($request['user_info']);
                CardOperationLog::insert([
                    'user_id' => $params['user_info']['user_id'],
                    'card_id' => $cardInfo['card_id'],
                    'card_no' => $cardInfo['card_no'],
                    'params' => json_encode($request),
                    'ip_address' => $_SERVER['REMOTE_ADDR'],
                ]);

            }
            Db::commit();

            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    public static function recharge(array $params): bool
    {
        Db::startTrans();
        try {
            //计算团队余额是否大于开卡金额
            $userGroup = UserGroup::where('id', $params['user_info']['group_id'])->findOrEmpty();
            if (empty($userGroup)) {
                throw new \Exception('团队不存在');
            }
            $user_money = $userGroup->user_money;
            if (bccomp($user_money, $params['money'], 2) < 0) {
                throw new \Exception("余额不足");
            }

            $card = Card::where('card_id', $params['card_id'] ?? 0)->findOrEmpty();
            if ($card->isEmpty()) {
                self::setError('卡不存在');
                return false;
            }
            //卡充值
            $card->available_balance = bcadd($card->available_balance, $params['money'], 2);
            $card->save();

            // 记录账户流水
            AccountLogLogic::add(
                $params['user_info']['group_id'],
                AccountLogEnum::UM_DEC_ADMIN,
                AccountLogEnum::DEC,
                $params['money'],
                '',
                '卡id充值:' . $params['card_id'],
            );
            // 减少客户余额
            $userGroup = UserGroup::where('id', $params['user_info']['group_id'])->findOrEmpty();
            $userGroup->user_money -= $params['money'];
            $userGroup->save();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function secure(array $params)
    {

        $cardInfo = Card::where('id', $params['id'])->findOrEmpty();
        if ($cardInfo->isEmpty()) {
            self::setError('卡片不存在');
            return false;
        }

        if ($cardInfo->group_id != $params['group_id']) {
            self::setError('无权限');
            return false;
        }
        $user = User::findOrEmpty($params['user_id']);
        if ($user->isEmpty()) {
            self::setError('用户不存在');
            return false;
        }

        $passwordSalt = Config::get('project.unique_identification');
        $oldPassword = create_password($params['password'], $passwordSalt);
        if ($oldPassword != $user['secure_password']) {
            self::setError('交易密码不正确');
            return false;
        }

        if ($cardInfo['group_id'] != $params['group_id']) {
            self::setError('无权限');
            return false;
        }

        $secure = decrypt($cardInfo->secure_msg);
        return json_decode($secure, true);

    }

    public static function change(array $params): bool
    {
        $card = Card::where('user_id', $params['user_id'])
            ->where('group_id', $params['group_id'])
            ->update(['user_id' => $params['new_user_id']]);

        return true;

    }

    public static function sync(array $params): bool
    {

        $cards = Card::where('group_id', $params['group_id'])
            ->select()->toArray();

        foreach ($cards as $card) {

            //万里付
            //ACTIVE：卡片可正常使用
            //FROZEN：卡片已冻结
            //CANCEL：卡片已注销
            if ($card['card_bin'] == 10 || $card['card_bin'] == 13) {
                $wordFirstType = match ($card['card_bin']) {
                    10 => 'worldfirst',
                    13 => 'worldfirst_hk',
                };
                $worldFirst = new WorldFirstService($wordFirstType);
                $worldFirstResult = $worldFirst->getCardDetail($card['card_id']);
                if (isset($worldFirstResult['cardStatus'])) {
                    $worldFirstResult = $worldFirst->getCardDetail($card['card_id']);
                    if (isset($worldFirstResult['cardStatus'])) {
                        $status = $worldFirstResult['cardStatus'] == 'ACTIVE' ? 1 : 0;
                        Card::where('id', $card['id'])->update(['status' => $status]);
                    }
                }
            }

            if ($card['card_bin'] == 11) {
                //空中云汇INACTIVE, ACTIVE, CLOSED
                $airwallex = new AirwallexService();
                $result = $airwallex->getCard($card['card_id']);

                if ($result['card_status'] == 'INACTIVE') {
                    Card::where('id', $card['id'])->update(['status' => 0]);
                } else if ($result['card_status'] == 'ACTIVE') {
                    Card::where('id', $card['id'])->update(['status' => 1]);
                } else if ($result['card_status'] == 'CLOSED') {
                    Card::where('id', $card['id'])->update(['status' => 0]);
                }
            }
            //slash:active, paused, closed, inactive
            if ($card['card_bin'] == 12 || $card['card_bin'] == 15) {
                $slashService = new SlashService($card['card_bin']);
                $result = $slashService->getCardInfo($card['card_id']);
                if ($result['status'] == 'paused') {
                    Card::where('id', $card['id'])->update(['status' => 0]);
                } else if ($result['status'] == 'active') {
                    Card::where('id', $card['id'])->update(['status' => 1]);
                } else if ($result['status'] == 'closed') {
                    Card::where('id', $card['id'])->update(['status' => 0]);
                }
            }

        }
        return true;
    }

    public static function code(array $params): array|false
    {
        $card_bin = $params['card_bin'] ?? 11;//默认空中云汇
        $card_id = $params['card_id'] ?? '';
        $card_no_last4 = $params['card_no_last4'];

        //万里付
        if ($card_bin == 10 || $card_bin == 13) {
            $where = [];
            if ($card_id) {
                $where['assetId'] = $card_id;
            } else {
                $where['cardNoLast4'] = $card_no_last4;
            }

            $result = TransactionNotification::where($where)
                ->whereTime('created_at', '-10 minutes')  // 最近10分钟
                ->order('created_at', 'desc')  // 按创建时间倒序
                ->find();

            if ($result && !empty($result['passcode'])) {
                return ['code' => $result['passcode']];
            }
        }

        //空中云汇
        if ($card_bin == 11) {
            return get_verification_code($params['card_no_last4']);
        }

        //SLASH
        if ($card_bin == 12 || $card_bin == 15) {
            if ($card_id == '') return false;
            $params = [
                'filter:cardId' => $card_id,
            ];
            $hasMore = true;
            while ($hasMore) {
                $slash = new SlashService($card_bin);
                $result = $slash->getTransaction($params);
                if (isset($result['items'])) {
                    foreach ($result['items'] as $item) {
                        $merchantCode = $item['merchantData']['categoryCode'] ?? 0;
                        if ($merchantCode == 7999) {
                            $code = substr($item['merchantData']['description'] ?? '', -4);
                            if (strlen($code) == 4) return ['code' => $code];
                        }
                    }
                }
                if (isset($result['metadata']['nextCursor'])) {
                    $params['cursor'] = $result['metadata']['nextCursor'];

                } else {
                    $hasMore = false;
                }
            }
        }

        return false;
    }

    //卡片使用率
    public static function utilization(array $params)
    {

        $cardInfo = Card::where('id', $params['id'])->findOrEmpty();
        if ($cardInfo->isEmpty()) {
            self::setError('卡片不存在');
            return false;
        }

        if ($cardInfo->group_id != $params['group_id']) {
            self::setError('无权限');
            return false;
        }

        if ($cardInfo['card_bin'] == 12 || $cardInfo['card_bin'] == 15) {
            $slashService = new SlashService($cardInfo['card_bin']);
            $result = $slashService->getCardUtilization($cardInfo['card_id']);
            if (isset($result['spend']['amountCents'])) return $result;
        }

        return false;

    }

    //卡片使用率
    public static function task(array $params)
    {

        return Card::where('group_id', $params['group_id'])
            ->where('secure_msg', NULL)
            ->count();

    }
}